from fastapi import APIRouter, HTTPException
from typing import Dict, Any
from src.core.progress_manager import ProgressManager
from src.infrastructure.log_decorators import log_operation

router = APIRouter()
progress_manager = ProgressManager()

@router.get("/progress/{task_id}")
async def get_download_progress(task_id: str) -> Dict[str, Any]:
    """
    获取下载进度
    
    Args:
        task_id: 下载任务ID
    
    Returns:
        进度信息字典，包含：
        - total_size: 总大小
        - downloaded_size: 已下载大小
        - speed: 下载速度
        - progress: 完成百分比
        - status: 任务状态
    """
    progress = progress_manager.get_progress(task_id)
    if not progress:
        raise HTTPException(
            status_code=404, 
            detail=f"Download task {task_id} not found"
        )
    return progress.to_dict()

@router.delete("/progress/{task_id}")
@log_operation("download_progress")
async def cancel_download(task_id: str) -> Dict[str, str]:
    """
    取消下载任务
    
    Args:
        task_id: 下载任务ID
    
    Returns:
        操作结果信息
    """
    try:
        await progress_manager.cancel_task(task_id)
        return {"message": "Download cancelled successfully"}
    except KeyError:
        raise HTTPException(status_code=404, detail="Task not found")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e)) 